package com.wdd.gateway;

import com.alibaba.fastjson.JSON;
import com.wdd.commmon.result.BaseResult;
import com.wdd.commmon.utils.Constants;
import com.wdd.gateway.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

/**
 * @author wdd
 */
@Slf4j
@Component
public class JwtTokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    private String[] blackArray = {};
    private String[] whiteArray = {
            "/sys/login",
            "/swagger-ui/index.html"
    };

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();
        // 跳过不需要验证的路径
        if (isWhite(url))
        {
            return chain.filter(exchange);
        }
        String token = getToken(exchange.getRequest());
        if (StringUtils.isBlank(token))
        {
            return setUnauthorizedResponse(exchange, "令牌不能为空");
        }
        // 解密获得username，用于和数据库进行对比
        String userName = JWTUtil.getUsername(token);
        if (StringUtils.isBlank(userName)) {
            return setUnauthorizedResponse(exchange, "token invalid");
        }
        //通过username从redis中查找用户对象
        String redisToken = stringRedisTemplate.opsForValue().get(userName);
        if(StringUtils.isBlank(redisToken)){
            return setUnauthorizedResponse(exchange,"token已过期，请重新登录!");
        }
        //如果redis中存在token,说明token未过期,自动延长7天
        if(StringUtils.equals(redisToken,token)){
            stringRedisTemplate.opsForValue().set(userName,token, Constants.POSTPONE_DAY, TimeUnit.DAYS);
        }
        Long userId = JWTUtil.getUserId(token);
        // 设置用户信息到请求
        ServerHttpRequest mutableReq = null;
        try {
            mutableReq = exchange.getRequest().mutate().header(Constants.USER_ID, String.valueOf(userId))
                    .header(Constants.USER_NAME, URLEncoder.encode(userName, Constants.UTF8)).build();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
        return chain.filter(mutableExchange);
    }

    private boolean isWhite(String requestUri) {
        return Arrays.stream(whiteArray).anyMatch(pattern -> antPathMatcher.match(pattern, requestUri));
    }

    private Mono<Void> setUnauthorizedResponse(ServerWebExchange exchange, String msg)
    {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        response.setStatusCode(HttpStatus.OK);

        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());

        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            return bufferFactory.wrap(JSON.toJSONBytes(BaseResult.error(msg)));
        }));
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request)
    {
        String token = request.getHeaders().getFirst("token");
        return token;
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
